<template>
  <div class="page-wrap">
    <div class="nav">
      <van-icon name="arrow-left" @click="router.back()" />
      <van-button
        :disabled="info ? false : true"
        round
        type="primary"
        @click="onPublish"
        >发布</van-button
      >
    </div>
    <div class="post-type">
      <van-tag
        v-for="item in type"
        :key="item"
        round
        type="primary"
        size="large"
        :plain="item !== selectType"
        @click="selectType = item"
        >{{ item }}
      </van-tag>
    </div>
    <p class="type-tip">*请选择帖子类别</p>
    <van-field
      class="comment"
      v-model="info"
      autosize
      type="textarea"
      maxlength="200"
      placeholder="快和校友一起分享新鲜事~"
      show-word-limit
    />
    <van-uploader
      v-show="imgList.length > 0"
      v-model="imgList"
      multiple
      deletable
      :max-count="imgNum"
      :max-size="10 * 1024 * 1024"
      @oversize="onOversize"
      :before-read="beforeRead"
    />
    <div class="bottom-bar">
      <van-uploader
        :max-size="10 * 1024 * 1024"
        @oversize="onOversize"
        :before-read="beforeRead"
        :after-read="onAddImage"
        :max-count="imgNum - imgList.length"
        multiple
      >
        <van-icon name="photo-o" />
      </van-uploader>
      <van-icon
        name="label-o"
        size="0.57rem"
        @click="
          show = true;
          getList();
        "
      />
      <van-tag
        :show="tagShow"
        closeable
        round
        size="medium"
        type="primary"
        @close="close"
      >
        {{ selectTag }}
      </van-tag>
    </div>
  </div>
  <van-popup
    class="tag-popup"
    v-model:show="show"
    position="bottom"
    :style="{ height: '70%' }"
    closeable
    :close-on-click-overlay="false"
    @click-close-icon="onClose"
    safe-area-inset-bottom
  >
    <header>添加话题</header>
    <van-search v-model="keyword" placeholder="搜索话题" @search="onSearch" />
    <div class="list-box">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        v-if="isSearched && searchRes.length"
      >
        <van-cell
          v-for="item in searchRes"
          :key="item"
          @click="onSelectTag(item)"
        >
          <template #title>
            <div class="custom-title">
              <img :src="type_img" alt="描述图片" />
              <span>{{ item }}</span>
            </div>
          </template>
          <template #right-icon>
            <van-button class="choose-btn" color="#f0f7ff" size="small"
              >选择</van-button
            >
          </template>
        </van-cell>
      </van-list>
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        v-if="!isSearched"
      >
        <van-cell v-for="item in tags" :key="item" @click="onSelectTag(item)">
          <template #title>
            <div class="custom-title">
              <img :src="type_img" alt="描述图片" />
              <span>{{ item }}</span>
            </div>
          </template>
          <template #right-icon>
            <van-button class="choose-btn" color="#f0f7ff" size="small"
              >选择</van-button
            >
          </template>
        </van-cell>
      </van-list>
      <van-empty
        v-if="isSearched && searchRes.length === 0"
        description="无相关话题"
      />
    </div>
  </van-popup>
</template>

<script>
import {
  Icon,
  Button,
  Field,
  Uploader,
  Popup,
  Search,
  Cell,
  List,
  Empty,
  Tag,
  Toast,
} from "vant";
import {
  publishPost,
  getPostsType,
  getTagList,
  getSearchTagList,
} from "@/api/BBSModuleAPI/posts";
import { uploadImage } from "@/utils/uploadImage";
import { onMounted, reactive, toRefs, watch, watchEffect } from "vue";
import { useRouter } from "vue-router";
export default {
  components: {
    [Icon.name]: Icon,
    [Button.name]: Button,
    [Field.name]: Field,
    [Uploader.name]: Uploader,
    [Popup.name]: Popup,
    [Search.name]: Search,
    [Cell.name]: Cell,
    [List.name]: List,
    [Empty.name]: Empty,
    [Tag.name]: Tag,
  },
  setup() {
    let data = reactive({
      info: "", //帖子内容
      show: false, //是否弹出话题弹窗
      isSearched: false, //是否处于已搜索状态
      tagShow: false, //是否展示话题标签
      loading: false, //列表加载
      finished: false, //列表结束
      keyword: "", //搜索关键词
      selectTag: "", //选中的话题标签
      selectType: "", //选中的帖子类别
      type: [], //所有的帖子类别
      type_img: "", //话题标签的描述图片
      imgList: [], //用户上传的图片
      tags: [], //话题标签列表
      imgNum: 3, //最大上传图片数量
      searchRes: [], //话题标签搜索结果列表
    });
    const router = useRouter();
    //获取当前用户的用户名和所在学校
    const username = sessionStorage.getItem("username");
    const college = sessionStorage.getItem("college");

    onMounted(() => {
      getPostsType().then(res => {
        data.type = res.type;
        data.selectType = res.type[0];
      });
    });
    const getList = () => {
      getTagList({ type: data.selectType }).then(res => {
        data.tags = res.tag;
        data.type_img = res.type_img;
        data.loading = false;
        data.finished = true;
      });
    };
    //监听关键词是否变为空
    watch(
      () => data.keyword,
      newVal => {
        if (newVal === "") {
          data.isSearched = false;
          data.tags = [];
          getList();
        }
      }
    );
    //监听话题弹窗是否被关闭
    watchEffect(() => {
      if (data.show === false) {
        data.keyword = "";
      }
    });
    //进行话题搜索
    const onSearch = () => {
      let { keyword, selectType } = data;
      getSearchTagList({ keyword, type: selectType }).then(res => {
        data.searchRes = res.tagList;
        data.isSearched = true;
        console.log(data.searchRes, data.isSearched);
      });
    };
    //选中话题标签
    const onSelectTag = tag => {
      data.selectTag = tag;
      data.show = false;
      data.tagShow = true;
    };
    //删除选中的话题标签
    const close = () => {
      data.tagShow = false;
      data.selectTag = "";
    };
    //关闭话题弹窗
    const onClose = () => {
      data.tags = [];
    };
    //上传图片
    const uploadImg = file => {
      return uploadImage(file.file.name, file.file);
    };
    //发布帖子
    const onPublish = async () => {
      const { info, selectTag, selectType, imgList } = data;
      let params = {
        username,
        info,
        type: selectType,
        college,
      };
      if (selectTag) {
        params.tag = selectTag;
      }
      if (imgList.length) {
        const info_img = [];
        for (let i = 0; i < imgList.length; i++) {
          try {
            const res = await uploadImg(imgList[i]);
            info_img.push(res.url);
          } catch (error) {
            Toast.fail("图片上传失败");
          }
        }
        params.info_img = info_img;
      }
      publishPost(params).then(res => {
        Toast.success("发布成功");
        router.back();
      });
    };
    //往图片数组添加图片
    const onAddImage = file => {
      if (Array.isArray(file)) {
        let num = data.imgList.length;
        data.imgList = [...data.imgList, ...file.slice(0, data.imgNum - num)];
      } else {
        data.imgList.push(file);
      }
    };
    //判断上传图片格式
    const beforeRead = file => {
      if (
        file.type === "image/jpeg" ||
        file.type === "image/jpg" ||
        file.type === "image/png"
      ) {
        return true;
      }
      Toast("请上传 jpg / jpeg / png 格式图片");
      return false;
    };
    //图片大小超出提示
    const onOversize = () => {
      Toast("图片大小不能超过10 MB");
    };

    return {
      router,
      ...toRefs(data),
      onSearch,
      onSelectTag,
      close,
      onClose,
      getList,
      onPublish,
      onAddImage,
      beforeRead,
      onOversize,
    };
  },
};
</script>

<style lang="less" scoped>
.page-wrap {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.nav {
  padding: 8px 14px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid gray;
  .van-button {
    padding: 0 12px;
    height: 28px;
    :deep(.van-button__text) {
      letter-spacing: 2px;
    }
  }
}
.post-type {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-top: 5px;
  padding: 0 8px;
  :deep(.van-tag) {
    margin: 0 8px 5px 0;
  }
}
.type-tip {
  margin: 0 10px;
  font-size: 10px;
  color: gray;
  text-align: left;
}
.comment {
  flex-grow: 1;
  :deep(.van-field__body) {
    height: 95%;
    .van-field__control {
      height: 100% !important;
    }
  }
}
.bottom-bar {
  display: flex;
  align-items: center;
  padding: 2px 12px;
  border-top: 1px solid #fafafa;
  background-color: #fafafa;
  :deep(.van-icon) {
    margin: 0 6px;
  }
}
:deep(.van-uploader__upload) {
  margin: 0 5px 5px;
}
.tag-popup {
  header {
    margin-top: 16px;
    font-size: 16px;
  }
  .list-box {
    height: 85%;
    overflow-y: scroll;
    .van-cell {
      align-items: center;
    }
    .custom-title {
      display: flex;
      img {
        width: 60px;
        height: 60px;
        margin-right: 10px;
        color: black;
      }
      span {
        padding-top: 5px;
      }
    }
    .choose-btn {
      color: rgb(59, 157, 196) !important;
    }
  }
}
</style>
